import axios from 'axios';

const baseUrl = 'http://47.108.129.64:8088/'
// const baseUrl = 'http://localhost:8088/'

axios.interceptors.response.use(
    response => {
        console.log(response, 'resssss');
        return response;
    },
    error => {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);

// 登录请求方法
const loginreq = (method, url, params) => {
    return axios({
        method: method,
        url: baseUrl + url,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        data: Object.assign({
            loginToken: localStorage.getItem('logintoken'),
            userName: localStorage.getItem('username')
        }, params),
        withCredentials: false,
        traditional: true,
        transformRequest: [
            function (data) {
                let ret = ''
                for (let it in data) {
                    ret +=
                        encodeURIComponent(it) +
                        '=' +
                        encodeURIComponent(data[it]) +
                        '&'
                }
                return ret
            }
        ]
    }).then();
};
// 通用公用post方法
const req = (method, url, params, headers = null) => {
    return axios({
        method: method,
        url: baseUrl + url,
        headers: headers === null ? { 'Content-Type': 'application/json;charset=UTF-8', } : headers,
        data: Object.assign({
            loginToken: localStorage.getItem('logintoken'),
            userName: localStorage.getItem('username')
        }, params),
        traditional: true,
    }).then(res => res.data);
};

// 通用公用get方法
const reqGet = (method, url, params) => {
    return axios({
        method: method,
        url: baseUrl + url,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            loginToken: localStorage.getItem('logintoken'),
            userName: localStorage.getItem('username')
        },
        params: Object.assign({
            loginToken: localStorage.getItem('logintoken'),
            userName: localStorage.getItem('username')
        }, params),
        traditional: true,
    }).then(res => res.data);
};

// 通用delete方法
const reqDelete = (url, params) => {
    return axios.delete(baseUrl + url, {
        params: Object.assign({
            loginToken: localStorage.getItem('logintoken'),
            userName: localStorage.getItem('username')
        }, params),
    })
        .then(res => res.data);
}

export {
    loginreq,
    req,
    reqGet,
    reqDelete
}